package com.taiyuan.tongcheng.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.DensityUtils;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.StringUtils;
import org.kymjs.kjframe.utils.SystemTool;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.taiyuan.tongcheng.adapter.CarKindAdapter;
import com.taiyuan.tongcheng.adapter.HalfStationAdapter;
import com.taiyuan.tongcheng.adapter.PayKindAdapter;
import com.taiyuan.tongcheng.application.TCBroadcastAction;
import com.taiyuan.tongcheng.bean.CargoOrderSimple;
import com.taiyuan.tongcheng.bean.CargoPrice;
import com.taiyuan.tongcheng.bean.SelectDate;
import com.taiyuan.tongcheng.bean.ServerStation;
import com.taiyuan.tongcheng.bean.StaListData;
import com.taiyuan.tongcheng.bean.SystemConfig;
import com.taiyuan.tongcheng.config.TcConfig;
import com.taiyuan.tongcheng.db.TcDbHelper;
import com.taiyuan.tongcheng.http.HTTPFieldConstant;
import com.taiyuan.tongcheng.http.HttpParamUtil;
import com.taiyuan.tongcheng.http.TcWebservice;
import com.taiyuan.tongcheng.http.WebData;
import com.taiyuan.tongcheng.jsonparser.TcJsParser;
import com.taiyuan.tongcheng.util.ACache;
import com.taiyuan.tongcheng.util.CommonUtil;
import com.taiyuan.tongcheng.util.TcUtil;
import com.taiyuan.tongcheng.util.TimeUtil;
import com.taiyuan.tongcheng.view.multichecklistview.MovingService;
import com.taiyuan.tongcheng.view.multichecklistview.MovingServiceAdapter;
import com.taiyuan.tongcheng.view.pickerview.OptionsPopupWindow;
import com.taiyuan.tongcheng.view.pickerview.OptionsPopupWindow.OnIMClickListener;
import com.taiyuan.tongcheng.view.pickerview.OptionsPopupWindow.OnOptionsSelectListener;
import com.tytc56.user.R;

public class ExpressActivity extends BaseActivity implements OnItemClickListener ,OnItemLongClickListener,OnGetRoutePlanResultListener{
	// ===== widget
	// 顶部
	@BindView(id = R.id.tv_common_title)
	private TextView titileTv;
	@BindView(id = R.id.btn_common_back, click = true)
	private Button backBtn;
	@BindView(id = R.id.tv_common_instruction,click=true)
	private TextView instruction;
	// 起开始位置
	@BindView(id = R.id.ll_freight_station)
	private LinearLayout llHalfway;
	@BindView(id=R.id.btn_add_half_way,click=true)
	private Button  addHalfWay;  
	@BindView(id=R.id.lv_half)
	private ListView halfLv;//途经点list
	//起始地
	@BindView(id=R.id.rl_express_start,click=true)
	private RelativeLayout  startRL;
	@BindView(id=R.id.rl_start_info)
	private RelativeLayout  startInfo;
	@BindView(id=R.id.tv_movingStart)
	private TextView  startInfoHint;
	@BindView(id=R.id.tv_start_add)
	private TextView  startAddress;
	@BindView(id=R.id.tv_start_user)
	private TextView  startConnectName;
	@BindView(id=R.id.tv_start_tel)
	private TextView  startConnectTel;
	
	@BindView(id=R.id.rl_express_destination,click=true)
	private RelativeLayout  destinationRL;
	@BindView(id=R.id.rl_end_info)
	private RelativeLayout  destinationInfo;
	@BindView(id=R.id.tv_moving_destination)
	private TextView  destinationHint;
	@BindView(id=R.id.tv_destination_add)
	private TextView  destinationAddress;
	@BindView(id=R.id.tv_destination_user)
	private TextView  destinationConnectName;
	@BindView(id=R.id.tv_destination_tel)
	private TextView  destinationConnectTel;

	// 服务
	@BindView(id = R.id.lv_service)
	private ListView serviceListView;
	@BindView(id = R.id.rl_cargo_service, click = true)
	private RelativeLayout serviceRl;
	@BindView(id = R.id.img_service_arrow)
	private ImageView serviceArrowImg;
	@BindView(id = R.id.img_anzhuang)
	private ImageView imgAnzhuang;
	@BindView(id = R.id.img_collection)
	private ImageView imgCollection;
	@BindView(id = R.id.img_reback)
	private ImageView imgReback;
	@BindView(id = R.id.img_moving)
	private ImageView imgMoving;
//	@BindView(id=R.id.)
	private TextView  serviceSelect;

	// 车型选择
	@BindView(id = R.id.lv_car_select)
	private ListView carStyleListView;
	@BindView(id = R.id.rl_car_style, click = true)
	private RelativeLayout carStyleRl;
	@BindView(id = R.id.img_carstyle_arrow)
	private ImageView carStyleArrowImg;
	@BindView(id = R.id.tv_car_item)
	private TextView carSelect;

	// 支付选择
	@BindView(id = R.id.lv_pay_select)
	private ListView payStyleListView;
	@BindView(id = R.id.rl_pay_style, click = true)
	private RelativeLayout payStyleRl;
	@BindView(id = R.id.img_pay_arrow)
	private ImageView payStyleArrowImg;
	@BindView(id = R.id.tv_pay_item)
	private TextView paySelect;
	//时间选择
	@BindView(id = R.id.rl_time_select, click = true)
	private RelativeLayout timeOderRl;
	@BindView(id = R.id.tv_moving_time)
	private TextView  timeTv;
	// 下一步按钮
	@BindView(id = R.id.btn_next, click = true)
	private Button btn;
	// 司机留言
	@BindView(id = R.id.rl_drvicer_msg, click = true)
	private RelativeLayout driver_msg;
	@BindView(id = R.id.tv_order_remarks)
	private TextView msgTv;
	//选择优惠卷
	@BindView(id=R.id.rl_coupon,click=true)
	private RelativeLayout  couponRl;
	@BindView(id=R.id.tv_coupon)
	private TextView couponRsTv;
	
	// 适配+容器
	private String[] serviceItem = new String[] {};
	private List<MovingService> serviceList = new ArrayList<MovingService>();
	private MovingServiceAdapter serviceAdapter;
	private CarKindAdapter carStyleAdapter;
	private PayKindAdapter carPayAdapter;
	private List<ImageView> serviceImglist = new ArrayList<ImageView>();
	private boolean clickState = false;
	ACache mCache;
	private CargoOrderSimple cargoOrderSimple = new CargoOrderSimple();
	private int halfway=0;
	//服务ID
	private List<Integer> serviceId = new ArrayList<Integer>();

	//起始点途径点信息
	private List<ServerStation> stationList=new ArrayList<ServerStation>();
	private HalfStationAdapter halfStationAdapter; 
	private List<ServerStation> allStationlist=new ArrayList<ServerStation>();
	private StaListData data=new StaListData();
	private ServerStation startSta=new ServerStation();
	private ServerStation destionationSta=new ServerStation();
	//地图相关，路径规划
	RoutePlanSearch  routePlanSearch;
	private int disTance;
	
	//输入页intent,
	private Intent inputStaIntent;//输入页intent
	private Intent couponIntent;//优惠卷
	//广播监听
	private IntentFilter  intentFilter ;
	//startActvityforResult返回状态码
	public static final int RES_CODE_START=0x01;
	public static final int RES_CODE_END  =0x02;
	public static final int RES_CODE_HALF =0x03;
	public static final int RES_CODE_DRIVER_MSG =0x04;
	public static final int RES_CODE_COUPON =0x05;
	//传递对象标签
	public  static final String TAG_STATION_INFO="station_info" ;
	public  static final String TAG_ORDER_PRICE="order_price" ;
	public  static final String TAG_ORDER_REQ_CODE="order_req" ;
	public  static final String TAG_SIMPLE_ORDER="TAG_SIMPLE_ORDER" ;
	
	//时间选择控件、 滚动选择框
	private ArrayList<String> options1Items = new ArrayList<String>();
	private ArrayList<ArrayList<String>> options2Items = new ArrayList<ArrayList<String>>();
	private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<ArrayList<ArrayList<String>>>();
//	TimePopupWindow pwTime;
	OptionsPopupWindow pwOptions;
	//data
	List<SelectDate> selectDateList; 
	
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_express);
	}

	@Override
	public void initData() {
		super.initData();
		initView();
		getSystemConfig();
		KJLoger.debug(spUtil.getImExpireTime()+"chaoshi");
		KJLoger.debug(spUtil.getWaitTimes()+"dengdai time");
		//地图 
		routePlanSearch=RoutePlanSearch.newInstance();
		inputStaIntent=new Intent(this,StationInputActivity.class);
		couponIntent=new Intent(this,CardListActivity.class);
		initServiceData();
		mCache = ACache.get(getApplicationContext());
		//增加广播监听
		initReceiver();
		//初始化发货人信息
		spUtil.setSendUserName(TcDbHelper.getUser(getApplicationContext()).getName());
		spUtil.setSendUserPhone(TcDbHelper.getUser(getApplicationContext()).getMobile());
	}
    /**
     * 
    * @Description: 监听1下单成功广播2 刷新服务项广播
    * @return void
    * @throws
    * @autour wzq
    * @date 2015-9-5 下午3:31:47
    * @update (date)
     */
	private void initReceiver() {
		intentFilter = new IntentFilter();
		intentFilter.addAction("service_freash_ui");
		intentFilter.addAction(TCBroadcastAction.SUCCESS_MAKE_ORDER);
		intentFilter.addAction(TCBroadcastAction.UI_REFREASH_TUJIN);
		registerReceiver(receiver, intentFilter);

	}

	
	private void initTimeWidget() {
		final Calendar now = Calendar.getInstance();
		// 时间选择器
		pwOptions = new OptionsPopupWindow(this,true);
		
		selectDateList = TimeUtil.getList(TcConfig.LIMIT_HOUR);
		for (int i = 0; i < selectDateList.size(); i++) {
			options1Items.add(selectDateList.get(i).getDateLable());
		}

		// 选项2
		for (int i = 0; i < selectDateList.size(); i++) {
			ArrayList<String> options2ItemsTem = new ArrayList<String>();

			if (i == 0) {
				for (int j = (now.get(Calendar.HOUR_OF_DAY)+2)%24; j < TcConfig.HOUR.length; j++) {
					options2ItemsTem.add(TcConfig.HOUR[j]);
				}
			} else {
				for (int j = 0; j < TcConfig.HOUR.length; j++) {
					options2ItemsTem.add(TcConfig.HOUR[j]);
				}
			}
			options2Items.add(options2ItemsTem);
		}

		// 选项3
		for (int i = 0; i < selectDateList.size(); i++) {
			ArrayList<ArrayList<String>> options3ItemsBitemp = new ArrayList<ArrayList<String>>();

			for (int j = 0; j < TcConfig.HOUR.length; j++) {
				ArrayList<String> options3ItemsTem = new ArrayList<String>();
				options3ItemsTem.add("0");
				options3ItemsTem.add("30");
				options3ItemsBitemp.add(options3ItemsTem);
			}
			options3Items.add(options3ItemsBitemp);
		}

		// 三级联动效果
		pwOptions.setPicker(options1Items, options2Items, options3Items, true);
		// 设置默认选中的三级项目
		pwOptions.setSelectOptions(0, 0, 0);
		// 监听确定选择按钮
		pwOptions.setOnoptionsSelectListener(new OnOptionsSelectListener() {

			@Override
			public void onOptionsSelect(int options1, int option2, int options3) {
				// 返回的分别是三个级别的选中位置
				KJLoger.debug(options1 + "ss" + option2 + "ss" + options3);
				StringBuilder builder = new StringBuilder();
				KJLoger.debug(builder.toString());
				String tx = options1Items.get(options1)
						+ options2Items.get(options1).get(option2)
						+ options3Items.get(options1).get(option2)
								.get(options3);
				KJLoger.debug(selectDateList.get(options1).getDateValue()+TcConfig.HOUR_VALUE[option2]+TcConfig.MINUTE_VALUE[options3]);
				timeTv.setText(tx);
				if(options1==0){
					cargoOrderSimple.setErviceDate(selectDateList.get(options1).getDateValue()+TcConfig.HOUR_VALUE[((now.get(Calendar.HOUR_OF_DAY)+3+option2)%24)]+TcConfig.MINUTE_VALUE[options3]);
					KJLoger.debug(TcConfig.HOUR_VALUE[((now.get(Calendar.HOUR_OF_DAY)+3+option2)%24)]);
				}else{
					cargoOrderSimple.setErviceDate(selectDateList.get(options1).getDateValue()+TcConfig.HOUR_VALUE[option2]+TcConfig.MINUTE_VALUE[options3]);
					
				}
				KJLoger.debug(cargoOrderSimple.getErviceDate());
			}
		});

		pwOptions.setOnIMClickLIstener(new OnIMClickListener() {

			@Override
			public void onImclick(int falg) {
				if (falg == 1) {
					timeTv.setText("现在");
					cargoOrderSimple.setIsImFalg(1);
					cargoOrderSimple.setErviceDate(StringUtils.getDataTime("yyyy-MM-dd HH:mm:ss"));
				}
			}
		});
	
		
	}
	
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if ("service_freash_ui".equals(intent.getAction())) {
				refreshServiceUi(serviceAdapter.getSelect());
			}
			if(TCBroadcastAction.SUCCESS_MAKE_ORDER.equals(intent.getAction())){
				ExpressActivity.this.finish();
			}
			if(TCBroadcastAction.UI_REFREASH_TUJIN.equals(intent.getAction())){
				int position=intent.getIntExtra(halfStationAdapter.TAG_TUJIN_POSITON, 0);
				deleteHalfStation(position);
			}
		}
	};

	/**
	* @Description: 初始化服务选项
	* @return void
	* @throws
	* @autour wzq
	* @date 2015-9-5 下午3:24:15
	* @update (date)
	 */
	private void initServiceData() {
		serviceItem = getResources().getStringArray(R.array.cargo_service);
		for (int i = 0; i < serviceItem.length; i++) {
			MovingService itemData = new MovingService();
			itemData.setServiceId(i);
			itemData.setSetviceContent(serviceItem[i]);
			serviceList.add(itemData);
		}
		serviceImglist.add(imgAnzhuang);
		serviceImglist.add(imgMoving);
		serviceImglist.add(imgReback);
		serviceImglist.add(imgCollection);
	}
	
	@Override
	public void initWidget() {
		super.initWidget();
		initView();
		initTimeWidget();
		startSta=(ServerStation)getIntent().getSerializableExtra(MainActivitySlide.LABLE_START_STA);
		startSta.setReceiver(TcDbHelper.getUser(getApplicationContext()).getName());
		startSta.setReceiverMobile(TcDbHelper.getUser(getApplicationContext()).getMobile());
		refreashStartStaInfo();
		// 时间选择器
		// 初始化服务
		serviceAdapter = new MovingServiceAdapter(this, serviceList,
				serviceListView);
		serviceListView.setAdapter(serviceAdapter);
		serviceListView.setItemsCanFocus(true);
		serviceListView.setClickable(true);
		serviceListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				refreshServiceUi(serviceAdapter.getSelect());
				ViewInject.toast("*****onitem********");
			}

		});

		carStyleAdapter = new CarKindAdapter(this);
		carStyleListView.setAdapter(carStyleAdapter);
		carStyleListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				carStyleAdapter.setSlectPositon(arg2);
				carStyleAdapter.notifyDataSetChanged();
				carSelect.setText(carStyleAdapter.carName[arg2]);
				carStyleListView.setVisibility(View.GONE);
			}
		});
		carSelect.setText(carStyleAdapter.carName[0]);
		// 初始化支付方式
		carPayAdapter = new PayKindAdapter(this);
		payStyleListView.setAdapter(carPayAdapter);
		payStyleListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				carPayAdapter.setSlectPositon(position);
				paySelect.setText(PayKindAdapter.payName[position]);
				payStyleListView.setVisibility(View.GONE);
			}
		});
		paySelect.setText(getString(R.string.select));
		titileTv.setText(R.string.main_taxi_title);
		halfStationAdapter=new HalfStationAdapter(this, stationList);
		halfLv.setAdapter(halfStationAdapter);
		halfLv.setOnItemClickListener(this);
//		halfLv.setOnItemLongClickListener(this);
		//地图检索
		routePlanSearch.setOnGetRoutePlanResultListener(this);
	}

	/**
	 * 
	* @Description:刷新服务项界面
	* @param select
	* @return void
	* @autour wzq 
	* @date 2015-8-27 上午10:49:40
	* @update (date)
	 */
	private void refreshServiceUi(LinkedList<Boolean> select) {
		serviceId.clear();
		for (int i = 0; i < select.size(); i++) {
			if (select.get(i)) {
				serviceImglist.get(i).setVisibility(View.VISIBLE);
				serviceId.add(i+1);
			} else {
				serviceImglist.get(i).setVisibility(View.GONE);
			}
		}
	}

	
	/**
	 * 增加中转站,代码布局
	 */
	private void addFreightStation() {
//		//途径layout布局容器控件初始化。
//		LinearLayout.LayoutParams halfRlLp=new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,DensityUtils.dip2px(this, 50));
//		RelativeLayout rl = new RelativeLayout(this);
//		rl.setBackgroundResource(R.drawable.selector_list_item_);
//		//增加左边的Icon
//		ImageView imgView = new ImageView(this);
//		imgView.setImageResource(R.drawable.icon_halfway);
//		RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(DensityUtils.dip2px(this, 60)
//		,DensityUtils.dip2px(this, 50));
//		lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
//		lp1.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
//		// 位于父 View 的左边，在父 View 中水平居中
//		rl.addView(imgView, lp1);
//		LinearLayout.LayoutParams splitLp=new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,1);
//		View view =new View(this);
//		view.setBackgroundResource(R.drawable.split_line);
//		llHalfway.addView(view,splitLp);
//		llHalfway.addView(rl,halfRlLp);
	}

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.rl_cargo_service:

			if (clickState) {
				serviceArrowImg
						.setImageResource(R.drawable.icon_arrow_right_default);
				serviceListView.setVisibility(View.GONE);
				clickState = !clickState;
			} else {
				serviceArrowImg
						.setImageResource(R.drawable.icon_arrow_down_default);
				serviceListView.setVisibility(View.VISIBLE);
				clickState = !clickState;
			}

			break;
		case R.id.tv_common_instruction:
			Bundle  bundle =new Bundle();
			bundle.putInt(TcWebviewActivity.TAG_COMFROM, TcWebviewActivity.TAG_CARGO_INFORM);
			bundle.putString(TcWebviewActivity.TAG_TOP_TITLE, "使用说明");
			startActivity(TcWebviewActivity.class, bundle);
			break;
		case R.id.rl_car_style:
			if (carStyleListView.getVisibility() == View.GONE) {
				carStyleListView.setVisibility(View.VISIBLE);
				carStyleArrowImg
						.setImageResource(R.drawable.icon_arrow_down_default);
			} else {
				carStyleListView.setVisibility(View.GONE);
				carStyleArrowImg
						.setImageResource(R.drawable.icon_arrow_right_default);
			}
			break;
		case R.id.rl_pay_style:
			if (payStyleListView.getVisibility() == View.GONE) {
				payStyleListView.setVisibility(View.VISIBLE);
				payStyleArrowImg
						.setImageResource(R.drawable.icon_arrow_down_default);
			} else {
				payStyleListView.setVisibility(View.GONE);
				payStyleArrowImg
						.setImageResource(R.drawable.icon_arrow_right_default);
			}
			break;
		case R.id.rl_time_select:
			pwOptions.showAtLocation(timeOderRl, Gravity.BOTTOM, 0, 0);
			break;
			
		case R.id.rl_coupon:
			couponIntent.putExtra(CardListActivity.TAG_MONEY_CARD_FROM, 1);
       		startActivityForResult(couponIntent, RES_CODE_COUPON);
			break;
		case R.id.btn_next:
			allStationlist.clear();
			//收集用户输入信息
			collectCacheOrderInfo();
			
			if(inputCheck()){
				TcLoaddingDialog.show();
				getallStationKm();//检索站点途径点路劲
			}else{
//				showErroCustomToast("请检车输入参数");
			}
			break;
			
		case R.id.rl_drvicer_msg:
			startActivityForResult(new Intent(this, DriverMsgActivity.class), RES_CODE_DRIVER_MSG);
			break;
		case R.id.btn_add_half_way:
			 addhalfStation();
		     break;
		case R.id.rl_express_start:
			inputStaIntent.putExtra(TAG_STATION_INFO, startSta);
			inputStaIntent.putExtra(TAG_ORDER_REQ_CODE, RES_CODE_START);
			startActivityForResult(inputStaIntent, RES_CODE_START);
			break;
		case R.id.rl_express_destination:
			inputStaIntent.putExtra(TAG_STATION_INFO, destionationSta);
			inputStaIntent.putExtra(TAG_ORDER_REQ_CODE, RES_CODE_END);
			inputStaIntent.putExtra(TAG_SIMPLE_ORDER, cargoOrderSimple);
			startActivityForResult(inputStaIntent, RES_CODE_END);
			break;
		default:
			break;
		}
	}
	
	/**
	 * 
	* @Description: 收集用户输入信息
	* @return void
	* @throws
	* @autour wzq
	* @date 2015-9-28 上午10:16:49
	* @update (date)
	 */
	
	private void collectCacheOrderInfo() {
		cargoOrderSimple.setPayTypeId(carPayAdapter.getSelecPosition());
		StringBuilder builder =new StringBuilder(serviceId.toString()) ;
		builder.deleteCharAt(builder.lastIndexOf("["));
		builder.deleteCharAt(builder.lastIndexOf("]"));
		cargoOrderSimple.setExtraServiceids(builder.toString());
		cargoOrderSimple.setServiceidList(serviceId);
		cargoOrderSimple.setTruckTypeId(carStyleAdapter.getSelecPosition());
		startSta.setId(R.drawable.move_icon_start_active);
		allStationlist.add(startSta);
		//输入起始数据
		cargoOrderSimple.setStartCity(startSta.getCity());
		cargoOrderSimple.setStartCityCode(startSta.getCityCode());
		cargoOrderSimple.setStartLatitude(startSta.getLatitude());
		cargoOrderSimple.setStartLongitude(startSta.getLongitude());
		cargoOrderSimple.setStartPlace(startSta.getPlace());
		cargoOrderSimple.setStartProvince(startSta.getProvince());
		
		cargoOrderSimple.setEndCity(destionationSta.getCity());
		cargoOrderSimple.setEndCityCode(destionationSta.getCityCode());
		cargoOrderSimple.setEndLatitude(destionationSta.getLatitude());
		cargoOrderSimple.setEndLongitude(destionationSta.getLongitude());
		cargoOrderSimple.setEndPlace(destionationSta.getPlace());
		cargoOrderSimple.setEndProvince(destionationSta.getProvince());
		cargoOrderSimple.setReceiver(destionationSta.getReceiver());
		cargoOrderSimple.setReceiverMobile(destionationSta.getReceiverMobile());
		KJLoger.debug(destionationSta.getCity()+destionationSta.getProvince());
		allStationlist.addAll(stationList);
		allStationlist.add(destionationSta);
		data.setStationList(allStationlist);
		cargoOrderSimple.setMiddlePlaceCount(stationList.size());
		if(stationList.size()>0){
			cargoOrderSimple.setMiddlePlaceInfo(JSON.toJSONString(stationList));
		}else{
			cargoOrderSimple.setMiddlePlaceInfo("");
		}
		
		KJLoger.debug("carPayAdapter.getSelecPosition()"+carPayAdapter.getSelecPosition());
		KJLoger.debug("json=="+JSON.toJSONString(stationList));
		mCache.put("CARGO", cargoOrderSimple);
		mCache.put("ALLSTA",data);
		KJLoger.debug("开始"+startSta.toString());
		KJLoger.debug("结束"+destionationSta.toString());
		KJLoger.debug("falg"+	cargoOrderSimple.getIsImFalg());
	}

	/**
	 * 
	* @Description: 获取起点+路径点+
	* @return void
	* @throws
	* @autour Administrator
	* @date 2015-8-30 下午4:49:24 
	* @update (date)
	 */
	private void getallStationKm() {
		PlanNode stNode = PlanNode.withLocation(new LatLng(startSta.getLatitude(), startSta.getLongitude()));  
		PlanNode enNode = PlanNode.withLocation(new LatLng(destionationSta.getLatitude(), destionationSta.getLongitude()));
        List<PlanNode>  passByList =new ArrayList<PlanNode>();
        
        for (int i = 0; i < stationList.size(); i++) {
        	PlanNode  halfPlanNode = PlanNode.withLocation(new LatLng(stationList.get(i).getLatitude(),stationList.get(i).getLongitude()));
        	passByList.add(halfPlanNode);
        }
        
        DrivingRoutePlanOption drivingOption = new DrivingRoutePlanOption();  
//      
//        ECAR_AVOID_JAM
//        驾车策略： 躲避拥堵
//        ECAR_DIS_FIRST
//        驾乘检索策略常量：最短距离
//        ECAR_FEE_FIRST
//        驾乘检索策略常量：较少费用
//        ECAR_TIME_FIRST
//        驾乘检索策略常量：时间优先
//        drivingOption.policy(DrivingRoutePlanOption.DrivingPolicy.ECAR_FEE_FIRST);// 设置驾车路线策略  
        drivingOption.policy(DrivingRoutePlanOption.DrivingPolicy.ECAR_DIS_FIRST);// 设置驾车路线策略
//       drivingOption.policy(DrivingRoutePlanOption.DrivingPolicy.ECAR_TIME_FIRST);// 设置驾车路线策略  
        drivingOption.from(stNode);// 设置起点  
        drivingOption.to(enNode);// 设置终点  
        routePlanSearch.drivingSearch(drivingOption);// 发起驾车路线规划  
        if(stationList.size()>0){
        	drivingOption.passBy(passByList);
        	routePlanSearch.drivingSearch(drivingOption);
        }else{
        	routePlanSearch.drivingSearch(drivingOption);
        }
        
        
	}
	
	/**
	 * 
	* @Description: 增加途径点
	* @return void
	* @throws
	* @autour Administrator
	* @date 2015-8-30 下午4:46:25 
	* @update (date)
	 */
	private void addhalfStation() {
		if(stationList.size()<=TcConfig.halfStationLimit){
			ServerStation info = new ServerStation();
			info.setId(R.drawable.icon_halfway);
			stationList.add(info);
			LinearLayout.LayoutParams haltLisfLp =(LayoutParams)halfLv.getLayoutParams();
			haltLisfLp.height=stationList.size()* (DensityUtils.dip2px(this, 50)+1);
			halfLv.setLayoutParams(haltLisfLp);
			halfStationAdapter.notifyDataSetChanged();
			halfLv.setAdapter(halfStationAdapter);
		}else{
//			addHalfWay.setVisibility(View.GONE);
			ViewInject.toast("只能添加5个途径点");
		}
	}
	
	private void deleteHalfStation(int positon) {
		stationList.remove(positon);
		LinearLayout.LayoutParams haltLisfLp =(LayoutParams)halfLv.getLayoutParams();
		haltLisfLp.height=stationList.size()* DensityUtils.dip2px(this, 51);
		halfLv.setLayoutParams(haltLisfLp);
		halfStationAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case RES_CODE_START:
			if (resultCode == RESULT_OK) {
				startSta = (ServerStation)data.getSerializableExtra("STA_POI");
				refreashStartStaInfo();
			}
			break;
		case RES_CODE_END:
			if (resultCode == RESULT_OK) {
				destionationSta = (ServerStation)data.getSerializableExtra("STA_POI");
				destionationSta.setId(R.drawable.move_icon_end_default);
				if(StringUtils.isEmpty(destionationSta.getPlace())){
					destinationInfo.setVisibility(View.GONE);
					destinationHint.setVisibility(View.VISIBLE);
				}else{
					destinationInfo.setVisibility(View.VISIBLE);
					destinationHint.setVisibility(View.GONE);
					destinationAddress.setText(destionationSta.getPlace());
					destinationConnectName.setText(destionationSta.getReceiver());
					destinationConnectTel.setText(destionationSta.getReceiverMobile());
				}
			}
			break;
		case RES_CODE_HALF:
			if (resultCode == RESULT_OK) {
				ServerStation  halfStation= (ServerStation)data.getSerializableExtra("STA_POI");
				int postion = data.getIntExtra("POSITION",0);
//				ViewInject.toast(postion+"**");
				stationList.set(postion, halfStation);
				halfStationAdapter.notifyDataSetChanged();
			}
			break;
		case RES_CODE_DRIVER_MSG:
			if (resultCode == RESULT_OK) {
				String result = data.getStringExtra("MESSAGE");
				msgTv.setText(result);
				cargoOrderSimple.setNote(result);
			}
			break;
		case RES_CODE_COUPON:
			if (resultCode == RESULT_OK) {
				String result = data.getStringExtra(CardListActivity.TAG_CARD_NO);
				String price =data.getStringExtra(CardListActivity.TAG_CARD_PRICE);
				if(!StringUtils.isEmpty(result)){
					if(result.equals("no")){
						cargoOrderSimple.setMoneyCardCode("");;
						couponRsTv.setText(R.string.coupon_no_use);
						cargoOrderSimple.setCouponPrice(0.0);
					}else{
						cargoOrderSimple.setMoneyCardCode(result);
						cargoOrderSimple.setCouponPrice(Double.parseDouble(price));
						couponRsTv.setText("使用面额为"+price+"的优惠券");
					}
				}
			}
			break;

		default:
			break;
		}
	}

	
	private void refreashStartStaInfo() {
		if(StringUtils.isEmpty(startSta.getPlace())){
			startInfo.setVisibility(View.GONE);
			startInfoHint.setVisibility(View.VISIBLE);
		}else{
			startInfo.setVisibility(View.VISIBLE);
			startInfoHint.setVisibility(View.GONE);
			startAddress.setText(startSta.getPlace());
			startConnectName.setText(startSta.getReceiver());
			startConnectTel.setText(startSta.getReceiverMobile());
		}
	}
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		inputStaIntent.putExtra(TAG_STATION_INFO,stationList.get(arg2));
		inputStaIntent.putExtra(TAG_ORDER_REQ_CODE,RES_CODE_HALF);
		inputStaIntent.putExtra("POSITION",arg2 );
		startActivityForResult(inputStaIntent,RES_CODE_HALF);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2,
			long arg3) {
		showinformDialog("温馨提示", "确定要删除该途径点么？", new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				deleteHalfStation(arg2);
				cancelInformDialog();
			}
		}, new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				cancelInformDialog();
			}
		});
		
		return true;
	}
	
	/**
	 * 
	* @Description: 获取价格
	* @return void
	* @throws
	* @autour wzq
	* @date 2015-8-27 下午1:58:15
	* @update (date)
	 */
	private void getForecastPrice() {

		if (!inputCheck()) {
			return;
		}
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjh = new KJHttp(config);
		HttpParams params = HttpParamUtil.getCargoForecastPrice(getApplicationContext(), cargoOrderSimple);
		KJLoger.debug(cargoOrderSimple.getExtraServiceids());
		KJLoger.debug(cargoOrderSimple.getTotalKiloMeter()+"");
		kjh.post(TcWebservice.WEBSERVER_IP+TcWebservice.API.FREIGHT_GET_PRICE, params,
             new HttpCallBack() {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);

						String str;
						try {
							str = URLDecoder.decode(new String(t), "UTF-8");
							WebData webData = TcJsParser.getWedataData(str);
							if (webData.getStatus() == 1) {
								CargoPrice  price = JSON.parseObject(webData.getData(), CargoPrice.class);
								KJLoger.debug(price.toString());
								mCache.put(TAG_ORDER_PRICE, price);
							    if(TcLoaddingDialog.isShowing()){
							    	TcLoaddingDialog.dismiss();
							    	startActivity(ExpressOrderActivity.class);
							    }
							}else if(webData.getStatus()==-1){
								showErroCustomToast(webData.getMsg());
								GotoLogin();
							}else {
								showCustomToast(webData.getMsg());
							}
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}

					}

					@Override
					public void onFailure(int errorNo, String strMsg) {
						super.onFailure(errorNo, strMsg);
						if (errorNo == -1) {
							// 网络超时
							ViewInject.toast(strMsg);
						}
					}
				});
	}
	
	/***
	 * 
	* @Description: 检测输入
	* @return
	* @return boolean
	* @throws
	* @autour Administrator
	* @date 2015-8-30 下午9:07:44 
	* @update (date)
	 */
	private boolean inputCheck() {
//		检测输入内容的合法性
//		检查起始
		
		if(StringUtils.isEmpty(startSta.getPlace())){
			KJLoger.debug("isEmpty(startSta");
			showErroCustomToast(getString(R.string.error_null_start));
			return false;
		}
		
		if(StringUtils.isEmpty(destionationSta.getPlace())){
			KJLoger.debug("isEmpty(destionationSta");
			showErroCustomToast(getString(R.string.error_null_end));
			return false;
		}
		
		if(stationList.size()>0){
			for (int i = 0; i < stationList.size(); i++) {
				if(StringUtils.isEmpty(stationList.get(i).getPlace())){
					showErroCustomToast(getString(R.string.error_null_middle));
					return false;
				}
			}
		}
		
		if(StringUtils.isEmpty(cargoOrderSimple.getErviceDate())){
			KJLoger.debug("isEmpty(getErviceDate");
			showErroCustomToast(getString(R.string.error_null_time));
			return false;
		}
		
		if(cargoOrderSimple.getTruckTypeId()==0){
			KJLoger.debug("isEmpty(getTruckTypeId");
			showErroCustomToast(getString(R.string.error_null_time));
			return false;
		}
		
		if(cargoOrderSimple.getPayTypeId()==0){
			showErroCustomToast(getString(R.string.error_null_pay));
			return false;
		}
		
		return true;
	}

	@Override
	public void onGetWalkingRouteResult(WalkingRouteResult result) {
		// 获取步行线路规划结果
	}

	@Override
	public void onGetTransitRouteResult(TransitRouteResult result) {
		// 获取公交换乘路径规划结果
	}

	@Override
	public void onGetDrivingRouteResult(DrivingRouteResult result) {
		
		if(result!=null){
			disTance=0;
			// 获取驾车线路规划结果
			List<DrivingRouteLine>  list = result.getRouteLines();
			for (int i = 0; i < list.size(); i++) {
				disTance+=list.get(i).getDistance();
			}
			cargoOrderSimple.setTotalMeter(disTance);
			double meter=Math.round(disTance/100d)/10d;
			cargoOrderSimple.setTotalKiloMeter(DoubleToInt(meter));
			KJLoger.debug("gongli== "+meter+"=后="+DoubleToInt(meter));
			
			showErroCustomToast("总公里数："+cargoOrderSimple.getTotalKiloMeter());
			//如果计大于0算得出的公里数
			if(cargoOrderSimple.getTotalKiloMeter()>0){
				getForecastPrice();
			}
//			ViewInject.toast("公里数"+cargoOrderSimple.getTotalKiloMeter());
		}
	}
	
	/**
	 * 
	 * @param f
	 * @return 获取整数
	 */
	public int DoubleToInt(double f){
	    int i = 0;
	    if(f>0) //正数
	      i = (int)(f*10 + 10)/10;
	    return i;

	}
	
	
	// 时间转换
	public static String timeFormatter(int minute) {
		if (minute < 60) {
			return minute + "分钟";
		} else if (minute % 60 == 0) {
			return minute / 60 + "小时";
		} else {
			int hour = minute / 60;
			int minute1 = minute % 60;
			return hour + "小时" + minute1 + "分钟";
		}
	}
	
	
	 /**
     * 获取系统配置信息
     */
    private void getSystemConfig() {
    	
    	HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
    	KJHttp kjHttp = new KJHttp(config);
		HttpParams params = HttpParamUtil.getSystemConfig(getApplicationContext());
		kjHttp.post(TcWebservice.WEBSERVER_IP + TcWebservice.API.APP_GETCONFIG,
				params, new HttpCallBack() {
					@Override
					public void onFailure(int errorNo, String strMsg) {
						super.onFailure(errorNo, strMsg);
					}
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						try {
							String response = URLDecoder.decode(t, "UTF-8");
							KJLoger.debug(response);
							WebData data = new WebData();
							data = TcJsParser.getWedataData(response);
							if (data.getStatus() == 1) {
								 SystemConfig  config=JSON.parseObject(data.getData(), SystemConfig.class);
								   if(!StringUtils.isEmpty(config.getCallImZcNoResTimes())){
									   spUtil.setWaitTimes(Integer.parseInt(config.getCallImZcNoResTimes()));
								   }
								   if(!StringUtils.isEmpty(config.getImExpireTime())){
									   spUtil.setImExpireTime(1000*Integer.parseInt(config.getImExpireTime()));
								   }
								   if(!StringUtils.isEmpty(config.getBjDiscountValue())){
									   spUtil.setBjDiscount(config.getBjDiscountValue());
								   }
							} else {
								
							}

						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					}
					@Override
					public void onFinish() {
						super.onFinish();
					}
				});

	}
}
